<?php
/**
 * Created by PhpStorm.
 * User: JieHuiLong
 * Date: 2017/3/20
 * Time: 16:55
 */
//--------------------------------------
/*$url = $_SERVER['HTTP_REFERER'];
// 来路是*.baidu.com  跳转到company页面  不是*.baidu.com跳转到spread页面 http://spread.onlinelibrary.cn/admin/domain?gid=9
if(strpos($url,'webabc.top') != false || strpos($url,'ehuiben.com') != false || strpos($url,'onlinelibrary.cn') != false){
    echo "<h1>推广页！</h1>";
}*/
//是否显示推广页
$isSpread = true;
$spreadPage = "spread.php";//推广页
$companyPage = "company.php";//公司页

if (!empty($ips)) {
    $ip = get_iplong(_get_ip());//判断的ip
    foreach ($ips as $key => $obj) {
        $itemIpArr = explode('-', str_replace(',', '-', $obj));
        $ip_start = get_iplong(trim($itemIpArr[0])); //起始ip
        $ip_end = get_iplong(trim($itemIpArr[1]));//至ip
        if ($ip >= $ip_start && $ip <= $ip_end) {
            $isSpread = true;
            break;
        } else {
            $isSpread = false;
        }
    }
}
if ($_GET['debug'] === 'kk') {
    echo "<h1>判断的ip</h1>";
    var_dump($isSpread);
    echo "<br>";
}


//判断是否在推广时间 /false => no  else  => yes
if(!empty($delivery_time)){
    if(date('H') == '00'){
        $nowTime = 0;
    }else{
        $nowHour = str_replace('0','',date('H'));
    }
    if (strstr($delivery_time, $nowHour) === false ) $isSpread = false;
}

if ($_GET['debug'] === 'kk') {
    echo "<h1>判断是否在推广时间</h1>";
    var_dump($isSpread);
    echo '<br>判断是推广时间是否为空：';
    var_dump(empty($delivery_time));
    $nowHour = str_replace('0','',date('H'));

    echo '<br>判断当前是否是推广时间：' .$nowHour;
    
    var_dump(strstr($delivery_time, $nowHour));
    echo '<br>推广时间列表：';

    echo $delivery_time."<br>";
}
// 是否开户推广
if (intval($isGeneralize) == 0 || !$isSpread) {
    //显示审核
    $isSpread = false;
    if ($_GET['debug'] === 'kk') {
        echo "<h1>是否开户推广 -- 审核页</h1>";
        var_dump($data);
        var_dump($_COOKIE['wechat_num']);
        var_dump($_COOKIE['wx_nickname']);
        echo "<br>";
        var_dump($filePath);
        echo "<br>";
        var_dump($wxConfigPath);
        echo "<br>";
        echo "<h1>开始调用审核页</h1>";
        exit();
    }
    include($readCatalog . '/company.php');
    exit();
}
//--------------------------------------
//终端设备判断 return bool true:推广 false：审核
$judgeDevice = judgeDevice($device_type);
//投放地区判断 return bool true:推广 false：审核
$judgeArea = judgeArea($area_config, $area_list);
//渠道限制 return bool true:推广 false：审核
$judgeChannel = judgeChannel($channel);

if ($judgeDevice && $judgeArea && $judgeChannel) {
    if (!$go_to_type) {
        //不跳转
        $isSpread = true;
        // $_COOKIE['wechat_num'] = NULL;
        //获取随机微信号--------Start
        if ($_COOKIE['wechat_num'] != NULL && $_COOKIE['wx_nickname'] != NULL) {
            foreach ($wechatList as $keyWx => $objWx) {
                if ($objWx[0] === $_COOKIE['wechat_num']) {
                    $resWechat = $objWx;
                    break;
                }
            }
            if ($_GET['debug'] === 'kk') {
                echo "<h1>获取随机微信号 COOKIE= NULL</h1>";
                var_dump($resWechat);
                echo "<br>";
            }

        } else {
            if (!is_file($wxConfigPath)) {
                $newfile = fopen($wxConfigPath, w);
                chmod($wxConfigPath, 0777);
                fclose($newfile);
            }
            if ($_GET['debug'] === 'kk') {
                echo "<h1>is_file wxConfig.php</h1>";
                var_dump($resWechat);
                echo "<br>";
            }
            include($wxConfigPath);
            if (!empty($wechatListConfig)) $wechatList = $wechatListConfig;

            //获取随机微信号
            $resWechat = getRandWechat($wechatList);

            if ($_GET['debug'] === 'kk') {
                echo "<h1>获取随机微信号 throught wxConfig.php</h1>";
                var_dump($resWechat);
                echo "<br>";
            }
            //是否进行重置微信号数组
            if ($resWechat === true) {
                foreach ($wechatList as $keyWxRest => $objWxRest) {
                    $objWxRest[3] = $objWxRest[2];
                    $wechatList[$keyWxRest] = $objWxRest;
                }
                //获取随机微信号
                $resWechat = getRandWechat($wechatList);
            }

            if (empty($resWechat)) {
                $resWechat = ["SSGW17950", "佳佳", "5", "50", "9:00", "18:00"];
            }
            foreach ($wechatList as $keyWx => $objWx) {
                if ($resWechat[0] === $objWx[0] && $objWx[3] > 0) {
                    $objWx[3] = (int)$objWx[3] - 1;
                    $wechatList[$keyWx] = $objWx;
                    break;
                }
            }
            $isRest = true;
            foreach ($wechatList as $keyRest => $objRest) {
                if ($objRest[3] != 0) {
                    $isRest = false;
                    break;
                }
            }

            if ($isRest) {
                foreach ($wechatList as $keyWxRest => $objWxRest) {
                    $objWxRest[3] = $objWxRest[2];
                    $wechatList[$keyWxRest] = $objWxRest;
                }
            }
            setcookie("wechat_num", $resWechat[0]);
            setcookie("wx_nickname", $resWechat[1]);

            //重新写入新的微信号---Start
            $out_weixin .= "//Start---配置微信号";
            $out_weixin .= "\n //微信号，微信昵称，默认随机值，随机值剩余次数，客服上线时间，客服下线时间 \n";
            $out_weixin .= '$wechatList=' . "[\n";
            foreach ($wechatList as $key => $obj) {
                $obj = '["' . str_replace(',', '","', join(',', $obj)) . "\"],\n";
                $out_weixin .= $obj;
            }
            $out_weixin .= "];\n";
            $out_weixin .= "//End---配置微信号";
            $domain = $_SERVER['HTTP_HOST'];
            $filePath = 'index.php';

            if (is_file($wxConfigPath)) {
                $out_weixin_Config = "<?php \n" . str_replace('wechatList', 'wechatListConfig', $out_weixin) . "\n ?> \n";
                file_put_contents($wxConfigPath, $out_weixin_Config);
            }

            if ($_GET['debug'] === 'kk') {
                echo "<h1>判断当前那些客服上班：</h1>";
                print_r($wechatList);

                var_dump($showWechat);

                echo "<br>";
            }


            //重新写入新的微信号---End
        }
        $data['wx_num'] = $resWechat[0] ? $resWechat[0] : $_COOKIE['wechat_num'];
        $data['wx_nickname'] = $resWechat[1] ? $resWechat[1] : $_COOKIE['wx_nickname'];
        $data['wx_rand'] = $resWechat[3];
        $data['wx_online'] = $resWechat[4];
        $data['wx_offline'] = $resWechat[5];
        //访问IP
        $data['client_ip'] = _get_ip();

        if ($_GET['debug'] === 'kk') {
            echo "<h1>推广页</h1>";
            var_dump($data);
            echo "<br>";
            var_dump($_COOKIE['wechat_num']);
            var_dump($_COOKIE['wx_nickname']);
            echo "<br>";
            var_dump($filePath);
            var_dump($wxConfigPath);
            echo "<br>";
        }
        //获取随机微信号--------End


    } else {
        //跳转其他分组
        header("Location: http://" . $jumpList[array_rand($jumpList)]);
        exit();
    }

} else {
    if ($_GET['debug'] === 'kk') {
            echo "<h1>设置条件访问，打开Debug模式</h1>";
            exit();
    }
    //显示审核
    $isSpread = false;
    include($readCatalog . '/company.php');
    exit();
}

/**
 * 将ip地址转换成int型
 * @param $ip  ip地址
 * @return number 返回数值
 */
function get_iplong($ip)
{
    //bindec(decbin(ip2long('这里填ip地址')));
    //ip2long();的意思是将IP地址转换成整型 ，
    //之所以要decbin和bindec一下是为了防止IP数值过大int型存储不了出现负数。
    return bindec(decbin(ip2long($ip)));
}

//终端设备类型限制 return bool true:推广 false：审核
function judgeDevice($device_type)
{
    $res = false;
    switch ($device_type) {
        case 1:
            //仅移动终端访问
            if (isMobile()) $res = true;
            break;
        case 2:
            //仅PC终端访问
            if (!isMobile()) $res = true;
            break;
        default:
            //不限制终端访问
            $res = true;
            break;
    }
    return $res;
}

//地区类型限制 return bool true:推广 false：审核
function judgeArea($area_config, $area_list)
{
    //设置不投放广告地区
    $res = true;
    if ($area_config) {
        $disableArea = explode(',', $area_list);
        if (IsArea($disableArea)) {
            //不投放广告
            $res = false;
        }
    }
    return $res;
}

//渠道限制 return bool true:推广 false：审核
function judgeChannel($channel)
{
    //渠道限制 null-不限制
    $res = true;
    if (!empty($channel)) {
        $channel = explode(',', $channel);
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        foreach ($channel as $key => $value) {
            if (strpos($user_agent, $value) === false) {
                //不投放广告
                $res = false;
                break;
            }
        }
    }
    return $res;
}

//当前在上班的客服
function getShowWechat($wechatList)
{
    $showWechat = array();
    foreach ($wechatList as $key => $obj) {
        $nowTime = strtotime(date('H:i'));
        $startTime = strtotime($obj[4]);
        $endTime = strtotime($obj[5]);
        if($startTime < $endTime){
            if ($startTime < $nowTime && $nowTime < $endTime) {
                $showWechat[] = $obj;
            }
        }else{
            echo $nowTime ."<br>".$endTime;
            if ($startTime < $nowTime || $nowTime < $endTime) {
                $showWechat[] = $obj;
            }
        }
    }
    return $showWechat;
}

function getRandWechat($wechatList)
{
//    获取当前在上班的微信号
    $showWechat = getShowWechat($wechatList);
    $res = $showWechat[array_rand($showWechat)];
    $isRest = true;
    if (empty($showWechat)) {
        //没有客服在线
        $res = $wechatList[array_rand($wechatList)];
        return $res;
    } else {
        //客服在线
        foreach ($showWechat as $keyRest => $objRest) {
            if ($objRest[3] != 0) {
                $isRest = false;
                break;
            }
        }
        if ($isRest === false) {
            if ($res[3] == 0) $res = getRandWechat($showWechat);
            return $res;
        } else {
            return true;
        }

        if ($_GET['debug'] === 'kk') {
            echo "<h1>客服在线</h1>";
            var_dump($showWechat);
            echo "<br>CookIE:<br>";
            var_dump($_COOKIE['wechat_num']);
            var_dump($_COOKIE['wx_nickname']);
            echo "<br>";
            echo "<br>";
        }

    }

}

//检测访问IP是否在所属地区
function IsArea($showArea = array('广东省广州市', '北京市'))
{
    if (empty($showArea)) return false;
    $ip = _get_ip();
    include($_SERVER["DOCUMENT_ROOT"] . "/locationSelect.class.php");
    $IpLocation = new IpLocation();
    $data = $IpLocation->getlocation($ip);
    $country = iconv("GBK", "UTF-8", $data['country']);
    foreach ($showArea as $key => $value) {
        if ($value == $country) {
            return true;
            break;
        }
    }
    return false;
}

/*获取客户端ip*/
function _get_ip()
{
    if (isset($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], "unknown"))
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], "unknown"))
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if (isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else if (isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else $ip = "";
    return ($ip);
}

//终端判断 return bool true:是 false：否
function isMobile()
{
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    if (isset ($_SERVER['HTTP_VIA'])) {
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

?>